package com.ruoyi.web.controller.award.competition;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.award.competition.*;
import com.ruoyi.system.service.award.competition.ICompetitionAwardInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 竞赛获奖信息Controller
 * 
 * @author ruoyi
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/award/competition")
public class CompetitionAwardInfoController extends BaseController
{
    @Autowired
    private ICompetitionAwardInfoService competitionAwardInfoService;

    /**
     * 查询竞赛获奖信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CompetitionAwardInfo competitionAwardInfo)
    {
        startPage();
        List<CompetitionAwardInfo> list = competitionAwardInfoService.selectCompetitionAwardInfoList(competitionAwardInfo);
        return getDataTable(list);
    }

    /**
     * 导出竞赛获奖信息列表
     */
    @Log(title = "竞赛获奖信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CompetitionAwardInfo competitionAwardInfo,
                       @RequestParam(required = false) String exportFields)
    {
        List<CompetitionAwardInfo> list = competitionAwardInfoService.selectCompetitionAwardInfoList(competitionAwardInfo);
        List<CompetitionVo> voList = new java.util.ArrayList<>();

        // 遍历主表数据
        for (CompetitionAwardInfo info : list) {
            // 获取竞赛主表信息
            String competitionName = info.getCompetitionName();
            String competitionRank = info.getCompetitionRank();
            String competitionLevel = info.getCompetitionLevel();
            String organizationUnit = info.getOrganizationUnit();
            String awardLevel = info.getAwardLevel();
            Date awardTime = info.getAwardTime();

            // 处理作品列表
            List<CompetitionAwardWorks> works = info.getWorks();
            if (works != null && !works.isEmpty()) {
                for (CompetitionAwardWorks work : works) {
                    // 获取作品信息
                    String workName = work.getWorkName();
                    String leaderName = work.getLeaderName();
                    String leaderGrade = work.getLeaderGrade();

                    // 处理指导老师（多老师用逗号拼接）
                    List<CompetitionAwardTeacher> teachers = work.getTeachers();
                    StringBuilder teacherNames = new StringBuilder();
                    if (teachers != null && !teachers.isEmpty()) {
                        for (int i = 0; i < teachers.size(); i++) {
                            teacherNames.append(teachers.get(i).getTeacherName());
                            if (i != teachers.size() - 1) {
                                teacherNames.append(",");
                            }
                        }
                    }

                    // 处理团队成员
                    List<CompetitionAwardTeamMembers> members = work.getTeamMembers();
                    if (members != null && !members.isEmpty()) {
                        // 有成员时，每个成员生成一条记录
                        for (CompetitionAwardTeamMembers member : members) {
                            CompetitionVo vo = new CompetitionVo();
                            // 设置竞赛主表字段
                            vo.setCompetitionName(competitionName);
                            vo.setCompetitionLevel(competitionLevel);
                            vo.setOrganizationUnit(organizationUnit);
                            vo.setAwardLevel(awardLevel);
                            vo.setAwardTime(awardTime);
                            // 设置作品字段
                            vo.setWorkName(workName);
                            vo.setLeaderName(leaderName);
                            vo.setLeaderGrade(leaderGrade);
                            // 设置指导老师
                            vo.setTeacherName(teacherNames.toString());
                            // 设置团队成员
                            vo.setMemberName(member.getMemberName());
                            vo.setMemberGrade(member.getMemberGrade());
                            voList.add(vo);
                        }
                    } else {
                        // 无成员时，生成一条空成员记录
                        CompetitionVo vo = new CompetitionVo();
                        vo.setCompetitionName(competitionName);
                        vo.setCompetitionLevel(competitionLevel);
                        vo.setOrganizationUnit(organizationUnit);
                        vo.setAwardLevel(awardLevel);
                        vo.setAwardTime(awardTime);
                        vo.setWorkName(workName);
                        vo.setLeaderName(leaderName);
                        vo.setLeaderGrade(leaderGrade);
                        vo.setTeacherName(teacherNames.toString());
                        vo.setMemberName("");
                        vo.setMemberGrade("");
                        voList.add(vo);
                    }
                }
            } else {
                // 无作品时，生成一条基础记录
                CompetitionVo vo = new CompetitionVo();
                vo.setCompetitionName(competitionName);
                vo.setCompetitionLevel(competitionLevel);
                vo.setOrganizationUnit(organizationUnit);
                vo.setAwardLevel(awardLevel);
                vo.setAwardTime(awardTime);
                voList.add(vo);
            }
        }
        System.out.println(voList);

        // 生成voList后添加排序逻辑
        voList.sort(Comparator.comparing(CompetitionVo::getCompetitionName)
                .thenComparing(CompetitionVo::getCompetitionLevel)
                        .thenComparing(CompetitionVo::getOrganizationUnit)
                        .thenComparing(CompetitionVo::getAwardLevel)
                .thenComparing(CompetitionVo::getAwardTime));
        ExcelUtil<CompetitionVo> util = new ExcelUtil<CompetitionVo>(CompetitionVo.class);




        // 如果传递了导出字段，则进行处理
        if (StringUtils.isNotBlank(exportFields)) {
            // 将逗号分隔的字段转为数组，调用showColumn指定显示字段
            String[] fields = exportFields.split(",");
            util.showColumn(fields); // 关键：使用ExcelUtil已有的showColumn方法
        }
        util.exportExcel(response, voList, "竞赛获奖信息数据");
    }

    /**
     * 获取竞赛获奖信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(competitionAwardInfoService.selectCompetitionAwardInfoById(id));
    }

    /**
     * 新增竞赛获奖信息
     */
    @Log(title = "竞赛获奖信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CompetitionAwardInfo competitionAwardInfo)
    {
        return toAjax(competitionAwardInfoService.insertCompetitionAwardInfo(competitionAwardInfo));
    }

    /**
     * 修改竞赛获奖信息
     */
    @Log(title = "竞赛获奖信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CompetitionAwardInfo competitionAwardInfo)
    {
        return toAjax(competitionAwardInfoService.updateCompetitionAwardInfo(competitionAwardInfo));
    }

    /**
     * 删除竞赛获奖信息
     */
    @Log(title = "竞赛获奖信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(competitionAwardInfoService.deleteCompetitionAwardInfoByIds(ids));
    }
}
